package com.async.job;

import cn.hutool.core.collection.CollUtil;
import com.async.biz.AsyncBizService;
import com.async.domain.entity.AsyncReq;
import com.async.domain.service.AsyncReqService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * <p>
 * 异步执行消息job
 * </p>
 * @author yang
 * @date 2024/5/18
 */
@Slf4j
@Component
public class AsyncJob {

    @Autowired
    private AsyncReqService asyncReqService;

    @Autowired
    private AsyncBizService asyncBizService;


    /**
     * name = "AsyncJob"
     * cron = "0 0/2 * * * ?"
     * description = "异步执行失败重试定时任务"
     */
    @XxlJob("AsyncJob")
    public void execute() {
        // 找出所有执行失败的任务
        long start = System.currentTimeMillis();
        try {
            List<AsyncReq> asyncReqs = asyncReqService.listRetry();
            if (CollUtil.isEmpty(asyncReqs)){
                return;
            }
            asyncReqs.forEach(asyncReq -> asyncBizService.invoke(asyncReq));
        }catch (Exception e){
            log.error("异步执行失败重试定时任务异常", e);
        }finally {
            long end = System.currentTimeMillis();
            log.info("异步重试定时任务执行结束...... 用时：{}毫秒", end - start);
        }
    }

}